package org.lzfto.flink.demo.common.logger;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluatorBase;

/**
 * 自定义logback日志评估器
 * 支持一个属性expression（spel)
 * <pre>
 *   <bold>示例</bold>
 *   (#loggerName).startsWith("org.lzfto")
 * </pre>
 * 如果条件满足，则指定的日志可以被接受
 * @author lzfto
 * @created 2025年6月5日 13:53:29
 */
public class MyLogBackEvnEvalutor extends EventEvaluatorBase<ILoggingEvent>  {
	
	private String expression;

	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		System.out.println("初始化自定义logback评估器,expression="+expression);
		this.expression = expression;
		context = new StandardEvaluationContext();
		ExpressionParser parser = new SpelExpressionParser();
        expr = parser.parseExpression(expression);
	}
	
	private static Expression expr;
	private static StandardEvaluationContext context;

	@Override
	public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException {

		if (expression == null || expression.isEmpty()) {
            return false;
        }
 
        try {        	
            // 创建一个上下文，用于解析 SpEL 表达式
            //StandardEvaluationContext context = new StandardEvaluationContext();
            // 你可以在这里设置上下文变量，例如：
            context.setVariable("message", event.getMessage());
            context.setVariable("loggerName", event.getLoggerName());
            context.setVariable("level", event.getLevel().toString());
            context.setVariable("throwable", event.getThrowableProxy());
            return expr.getValue(context, Boolean.class);
        } catch (Exception e) {
            throw new EvaluationException("Failed to evaluate SpEL expression: " + expression, e);
        }
	}

}
